<template>
    <div class="DetailsBasicInformation">
      <Form @submit.native.prevent>
        <Row :gutter="16">
          <Col span="12" v-if="unlocking('客户管理', '2000001')">
            <FormItem label="客户姓名：" @keyup.enter.native="keyupEnterFun('customerName')">
              <span v-if="type != 'customerName'">{{basicInformatData.customerName || '-'}}</span>
              <Input id="formDealWithRefs" maxlength="15" v-if="type == 'customerName'" v-model="customerName" placeholder="请输入客户姓名" style="width: 200px" />
              <img v-if="type != 'customerName' && unlocking('客户管理', '3000005')" class="editFeatures" @click="FormDealWithFun('customerName')" src="@img/edit.png">
            </FormItem>
          </Col>
          <Col span="12" v-if="unlocking('客户管理', '2000002')">
            <FormItem label="性别：" @keyup.enter.native="keyupEnterFun()">
              <span v-if="type != 'genderVal'">{{basicInformatData.gender == 1 ? '男' : basicInformatData.gender == 2 ? '女' : '-' }}</span>
              <Select id="formDealWithRefs" v-if="type == 'genderVal'" v-model="genderVal" filterable style="width:200px" placeholder="请选择性别" >
                <Option v-for="(item, index) in genderValList" :value="item.val" :key="index">{{ item.name }}</Option>
              </Select>
              <img v-if="type != 'genderVal' && unlocking('客户管理', '3000005')" class="editFeatures" @click="FormDealWithFun('genderVal')" src="@img/edit.png">
            </FormItem>
          </Col>
          <Col span="12" v-if="unlocking('客户管理', '2000003')">
            <FormItem label="建档时间：" @keyup.enter.native="keyupEnterFun()">
              <span v-if="type != 'fileTime'">{{basicInformatData.createTime || '-'}}</span>
              <DatePicker id="formDealWithRefs" v-if="type == 'fileTime'" :clearable="false" type="datetime" format="yyyy-MM-dd HH:mm:ss" v-model="fileTime" placeholder="请选择建档时间" style="width: 200px" />
              <img v-if="type != 'fileTime' && unlocking('客户管理', '3000005')" class="editFeatures" @click="FormDealWithFun('fileTime')" src="@img/edit.png">
            </FormItem>
          </Col>
          <Col span="12" v-if="unlocking('客户管理', '2000004')">
            <FormItem label="留资号码：" @keyup.enter.native="keyupEnterFun('reservedNumber')">
              <span v-if="type != 'reservedNumber'">{{basicInformatData.customerPhone || '-'}}</span>
              <Input id="formDealWithRefs" v-if="type == 'reservedNumber'" v-model="reservedNumber" placeholder="请输入备用号码" style="width: 200px" />
              <img v-if="type != 'reservedNumber' && unlocking('客户管理', '3000005') && !basicInformatData.customerPhone" class="editFeatures" @click="FormDealWithFun('reservedNumber')" src="@img/edit.png">
            </FormItem>
          </Col>
          <Col span="12" v-if="unlocking('客户管理', '2000006')">
            <FormItem label="备用号码：" @keyup.enter.native="keyupEnterFun('alternateNumberVal')">
              <span v-if="type != 'alternateNumberVal'">{{basicInformatData.standbyPhone || '-'}}</span>
              <Input id="formDealWithRefs" v-if="type == 'alternateNumberVal'" v-model="alternateNumberVal" placeholder="请输入备用号码,多个中间逗号分隔" style="width: 200px" />
              <img v-if="type != 'alternateNumberVal' && unlocking('客户管理', '3000005')" class="editFeatures" @click="FormDealWithFun('alternateNumberVal')" src="@img/edit.png">
            </FormItem>
          </Col>
          <Col span="12" v-if="unlocking('客户管理', '2000007')">
            <FormItem label="微信号码：" @keyup.enter.native="keyupEnterFun('weChatIDVal')">
              <span v-if="type != 'weChatIDVal'">{{basicInformatData.wechat || '-'}}</span>
              <Input id="formDealWithRefs" v-if="type == 'weChatIDVal'" v-model="weChatIDVal" placeholder="请输入微信号,多个中间逗号分隔" style="width: 200px" />
              <img v-if="type != 'weChatIDVal' && unlocking('客户管理', '3000005')" class="editFeatures" @click="FormDealWithFun('weChatIDVal')" src="@img/edit.png">
            </FormItem>
          </Col>
          <Col span="12" v-if="unlocking('客户管理', '2000010')">
            <FormItem label="归属楼盘：">{{detailsRes.buildingAlias || '-'}}</FormItem>
          </Col>
          <Col span="12" v-if="unlocking('客户管理', '2000012')">
            <FormItem label="归属运营：">
              <span>{{(detailsRes.operationalName && detailsRes.operationalNameDept) ? detailsRes.operationalName+'（'+detailsRes.operationalNameDept+')' : detailsRes.operationalName ? detailsRes.operationalName : '-'}}</span>
            </FormItem>
          </Col>
          <Col span="12" v-if="unlocking('客户管理', '2000013')">
            <FormItem label="归属顾问：" @keyup.enter.native="keyupEnterFun()">
              <span v-if="type != 'ownedOperation'">{{(detailsRes.userName && detailsRes.userNameDept) ? detailsRes.userName+'（'+detailsRes.userNameDept+')' : detailsRes.userName ? detailsRes.userName : '-'}}</span>
              <Select id="formDealWithRefs" v-if="type == 'ownedOperation'" v-model="ownedOperation" filterable style="width:200px" placeholder="请选择归属顾问" >
                <Option v-for="(item, index) in businessUserList" :value="item.userId" :key="index">{{ item.userName }}</Option>
              </Select>
              <img v-if="type != 'ownedOperation' && unlocking('客户管理', '3000005')" class="editFeatures" @click="FormDealWithFun('ownedOperation')" src="@img/edit.png">
            </FormItem>
          </Col>
          <Col span="12" v-if="unlocking('客户管理', '2000014')">
            <FormItem label="归属接待：" @keyup.enter.native="keyupEnterFun()">
              <span v-if="type != 'attributionReception'">{{(detailsRes.belongReceptionIdName && detailsRes.belongReceptionDept) ? detailsRes.belongReceptionIdName+'（'+detailsRes.belongReceptionDept+')' : detailsRes.belongReceptionIdName ? detailsRes.belongReceptionIdName : '-'}}</span>
              <Select id="formDealWithRefs" v-if="type == 'attributionReception'" v-model="attributionReception" filterable style="width:200px" placeholder="请选择归属接待" >
                <Option v-for="(item, index) in businessUserList" :value="item.userId" :key="index">{{ item.userName }}</Option>
              </Select>
              <img v-if="type != 'attributionReception' && unlocking('客户管理', '3000005')" class="editFeatures" @click="FormDealWithFun('attributionReception')" src="@img/edit.png">
            </FormItem>
          </Col>
          <Col span="12" v-if="unlocking('客户管理', '2000015')">
            <FormItem label="来源渠道：" @keyup.enter.native="keyupEnterFun()">
              <span v-if="type != 'sourceChannel'">{{basicInformatData.sourceIdName || "-"}}</span>
              <Select id="formDealWithRefs" v-if="type == 'sourceChannel'" v-model="sourceChannel" filterable style="width:200px" placeholder="请选择来源渠道" >
                <Option v-for="(item, index) in sourceChannelList" :disabled="item.validate == 2" :value="item.channelId" :key="index">{{ item.channelName }}</Option>
              </Select>
              <img v-if="type != 'sourceChannel' && unlocking('客户管理', '3000005')" class="editFeatures" @click="FormDealWithFun('sourceChannel')" src="@img/edit.png">
            </FormItem>
          </Col>
        </Row>
      </Form>
      <!-- 若有客户进度到访以上的，则不可保存成功 -->
      <Modal width="400" v-model="customerVisitState" :mask-closable="false" :footerHide="true" :closable='false' class="customerVisitModel">
        <p style=" font-size: 18px;">客户已到访案场</p>
        <p>归属人：{{successInfo.username}}({{successInfo.orgName}})</p>
        <p>楼盘：{{successInfo.buildingAlias}}</p>
        <div class="footer">
          <Button type="primary" @click="customerVisitOK">OK</Button>
        </div>
      </Modal>
    </div>
</template>
<script>
  import { customerDetailsInfo, businessUsers, customeruserEdit, aggChannelGroupList, userCustomerCheckPhone, userGetBelongingUser, customerFindSpecial } from "@/api/customerManagement.js";
  import Helper from "@/common/helper.js";
  import tool from "@/common/tool.js"
  export default {
    components: {

    },
    props: ['servicePersonnelId'],
    data() {
        return {
          detailsRes: '',
          businessUserList: [],
          registrationNumber: '',
          reservedNumber: '',
          fileTime: '',
          sourceChannel: '',
          sourceChannelList: [],
          basicInformatData: '',
          customerVisitState: false,
          type: '',
          genderVal: '',
          genderValList: [{name: '男', val: '1'}, {name: '女', val: '2'}],
          ownedOperation: '',
          attributionReception: '',
          alternateNumberVal: '',
          customerName: '',
          weChatIDVal: '',
          successInfo: ''
        }
    },
    methods: {
      // 若有客户进度到访以上的，则不可保存成功
      customerVisitOK() {
        this.customerVisitState = false
      },
      // 编辑功能
      FormDealWithFun(type) {
        if (!this.servicePersonnelId.storeManager) {
          this.$Message.warning('您无操作权限，请联系系统管理员')
          return false
        }
        this.initData()
        this.type = type
      },
      // Input 回车事件
      keyupEnterFun(val) {
        // 留资号码
        if (val == 'reservedNumber') {
          if (!this.reservedNumber) {
            return false
          }
          if (this.reservedNumber.length > 15) {
            this.$Message.warning('不可超过15位')
            return false
          } else if (!(/^[0-9]*$/.test(this.reservedNumber))) {
            this.$Message.warning('请输入数字')
            return false
          }
          this.$Modal.confirm({
            title: '保存确认',
            content: `<p>警示：请再次确认录入的留资号码是否正确，一旦录入，不可修改！</p><p style="margin-top: 10px;">留资号码：${this.reservedNumber}</p>`,
            okText: '确认保存',
            cancelText: '我再想想',
            onOk: () => {
              userCustomerCheckPhone({
                buildingId: this.servicePersonnelId.buildingId,
                phone: this.reservedNumber
              }).then(res=>{
                if (res == 2) {
                  userGetBelongingUser({
                    customerType: this.servicePersonnelId.customerType == 36 ? 1 : 2,
                    phone: this.reservedNumber || '',
                    customerId: this.$route.query.customerId
                  }).then(resl=>{
                    this.type = ''
                    if (resl) {
                      this.successInfo = resl
                      this.customerVisitState = true
                    } else {
                      let parms = {
                        userCustomerId: this.$route.query.userCustomerId,
                        buildingId: this.servicePersonnelId.buildingId,
                        customerPhone: this.reservedNumber
                      }
                      customeruserEdit(parms).then(res=>{
                        this.$Message.success('修改成功!');
                        setTimeout(()=>{
                          this.$emit("headRefreshFun")
                        }, 1000)
                        this.initData()
                      }).catch(err=>{
                        this.$Message.error(err)
                      })
                    }
                  }).catch(err=>{
                    this.$Message.error(err)
                  })
                } else if (res == 1) {
                  this.$Message.warning('该客户在当前楼盘下已录入手机号码！')
                }
              }).catch(err=>{
                this.$Message.error(err)
              })
            },
            onCancel: () => {}
          });
        } else {
          if (val == 'customerName') {
            if (this.customerName) {
              if (this.customerName.length > 20) {
                this.$Message.warning('不可超过20个字符')
                return false
              } else if (!(/^[\u4e00-\u9fa5_a-zA-Z]+$/.test(this.customerName))) {
                this.$Message.warning('请输入中英文')
                return false
              }
            }
          }
          if (this.alternateNumberVal) {
            if (!(/^[\d,]*$/.test(this.alternateNumberVal))) {
              this.$Message.warning('请输入数字、逗号')
              return false
            } else if (this.alternateNumberVal.indexOf(",") != -1) {
              let NumberBoolean = this.alternateNumberVal.split(',').every(function (val,index,arr) {
                return val.length <= 15
              })
              if (!NumberBoolean) {
                this.$Message.warning('每个逗号内的电话号码，限制15位')
                return false
              }
            } else {
              if (this.alternateNumberVal.length > 15) {
                this.$Message.warning('单个留资号码只能输入15位')
                return false
              }
            }
          }
          if (this.weChatIDVal) {
            if (!(/^[\a-\z\A-\Z0-9\u4E00-\u9FA5\.\,\?\<\>\。\，\-\——\=\;\@\！\!\+\$\#\%\*\（\)\|\~\&\{\}\"\“\”\`\_]+$/.test(this.weChatIDVal))) {
              this.$Message.warning('请输入中英文、数字、特殊符号')
              return false
            } else if (this.weChatIDVal.indexOf(",") != -1) {
              let NumberBoolean = this.weChatIDVal.split(',').every(function (val,index,arr) {
                return val.length <= 15
              })
              if (!NumberBoolean) {
                this.$Message.warning('每个逗号内的微信号，限制20位')
                return false
              }
            } else {
              if (this.weChatIDVal.length > 15) {
                this.$Message.warning('单个微信号只能输入20位')
                return false
              }
            }
          }
          userGetBelongingUser({
            customerType: this.servicePersonnelId.customerType == 36 ? 1 : 2,
            phone: this.servicePersonnelId.phone || '',
            customerId: this.$route.query.customerId
          }).then(resl=>{
            let parms = {
              userCustomerId: this.$route.query.userCustomerId,
              buildingId: this.servicePersonnelId.buildingId,
              customerName: this.customerName,
              gender: this.genderVal,
              createTime: (this.fileTime && Helper.timestampToTime(this.fileTime)) || '',
              standbyPhone: this.alternateNumberVal,
              wechat: this.weChatIDVal,
              userNameId: this.ownedOperation,
              belongReceptionId: this.attributionReception,
              channelSource: this.sourceChannel
            }
            if (resl) {
              if (resl.userId == JSON.parse(tool.getStorage('userMess')).userId) {
                this.type = ''
                this.modifyDataList(parms)
              } else {
                this.successInfo = resl;
                console.log("客户已到达案场")
                this.customerVisitState = true;
                this.type = "";
              }
            } else {
              this.type = ''
              this.modifyDataList(parms)
            }
          }).catch(err=>{
            this.$Message.error(err)
          })
        }
      },
      modifyDataList(parms) {
        customeruserEdit(parms).then(res=>{
          this.$Message.success('修改成功!');
          this.initData()
          this.$emit("headRefreshFun")
        }).catch(err=>{
          this.$Message.error(err)
        })
      },
      // 点击页面
      documentDealWithFun(e) {
        const contextMenuBox = document.getElementById("formDealWithRefs");
        if (!e.target.classList.contains('editFeatures')) {
          if (contextMenuBox){
            if(!contextMenuBox.contains(e.target)) {
              this.keyupEnterFun(this.type)
            }
          }
        }
      },
      // 初始化获取数据
      initData() {
        Promise.all([businessUsers({
          page: 1,
          rows: 100,
          buildingId: this.servicePersonnelId.buildingId,
          positionType: 4
        }).then(res=>{
          if (res && res.list) {
            let dataList = res.list
            businessUsers({
              page: 1,
              rows: 100,
              buildingId: this.servicePersonnelId.buildingId,
              positionType: 2
            }).then(resV=>{
              if (resV && resV.list) {
                this.businessUserList = Object.assign({}, dataList, resV.list)
              } else {
                this.businessUserList = Object.assign({}, dataList)
              }
            }).catch(err=>{
              this.$Message.error(err)
            })
          } else {
            this.businessUserList = []
          }
        }).catch(err=>{
          this.$Message.error(err)
        }),aggChannelGroupList({cityCode: this.servicePersonnelId.cityCode}).then(res=>{
          this.sourceChannelList = res && res.list && res.list[0]?res.list[0].list:[];
        }).catch(err=>{
          this.$Message.error(err)
        })]).then( result =>{
          // 城市code，楼盘名称，归属楼盘，归属顾问
          customerFindSpecial({
            buildingId: this.servicePersonnelId.buildingId,
            customerId: this.$route.query.customerId,
            userCustomerId: this.$route.query.userCustomerId
          }).then(details => {
            this.detailsRes = details
            this.ownedOperation = details.userNameId
            this.attributionReception = details.belongReceptionId
          })
          // 获取基本信息
          customerDetailsInfo({
            userCustomerId: this.$route.query.userCustomerId
          }).then(res=>{
            if (res) {
              res.sourceIdName = ""
              this.sourceChannelList.forEach((item) => {
                if (item.channelId == res.channelSource) {
                  res.sourceIdName = item.channelName
                }
              })
              this.basicInformatData = res
              // 修改数据返填
              this.customerName = res.customerName
              this.genderVal = res.gender
              this.fileTime = res.createTime
              this.reservedNumber = res.customerPhone
              this.alternateNumberVal = res.standbyPhone
              this.weChatIDVal = res.wechat
              this.sourceChannel = res.sourceId || ''
            }
          }).catch(err=>{
            this.$Message.error(err)
          })
        })
      }
    },
    computed: {

    },
    created() {

    },
    mounted() {
      document.addEventListener('click', this.documentDealWithFun)
    },
    destroyed() {
      document.removeEventListener('click', this.documentDealWithFun)
    },
    watch: {
      servicePersonnelId:{
        handler(newV,oldV){
          if (this.servicePersonnelId.servicePersonnelVal) {
            // 初始化获取数据
            this.initData()
          }
        },
        deep: true, //深度遍历
        immediate: true //默认false，设置为true会立即执行
      }
    },
  }
</script>
<style lang="scss" scoped>
.DetailsBasicInformation{
  .ivu-form-item{
    margin-bottom: 4px;
  }
  .editFeatures{
    vertical-align: middle;
    margin-left: 20px;
    cursor: pointer;
    display: inline-block;
  }
}
.customerVisitModel{
  p{
    margin-bottom: 10px;
  }
  .footer{
    padding-top: 20px;
    text-align: center;
    button{
      width: 120px;
      margin: 0 10px;
    }
  }
}
</style>
